package org.ee.rabbitmq.config;

import org.ee.rabbitmq.model.RabbitTopic;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @Author zlj
 * @Date 2025/11/10 22:45
 */
@Configuration
public class RabbitAutoConfig {

    @Bean
    public AmqpAdmin amqpAdmin(ConnectionFactory factory) {
        return new RabbitAdmin(factory);
    }

    /**
     * 提供统一的 RabbitTemplate
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
        return new RabbitTemplate(factory);
    }

    /**
     * 根据传入的主题动态创建绑定关系
     */
    public void declareTopic(AmqpAdmin admin, RabbitTopic topic) {
        Queue queue = new Queue(topic.getQueue(), true);
        DirectExchange exchange = new DirectExchange(topic.getExchange());
        Binding binding = BindingBuilder.bind(queue)
                .to(exchange)
                .with(topic.getRoutingKey());

        admin.declareExchange(exchange);
        admin.declareQueue(queue);
        admin.declareBinding(binding);
    }
}
